/**
 * 将 ArrayBuffer 转换为 Base64 字符串
 * @param buffer ArrayBuffer 数据
 * @param mimeType MIME 类型，默认为 'image/png'
 * @returns Base64 字符串
 */
export function bufferToBase64(buffer: ArrayBuffer, mimeType: string = 'image/png'): string {
  if (!buffer || !(buffer instanceof ArrayBuffer)) {
    throw new Error('Invalid buffer provided');
  }

  const bytes = new Uint8Array(buffer);
  let binary = '';
  
  for (let i = 0; i < bytes.byteLength; i++) {
    binary += String.fromCharCode(bytes[i] || 0);
  }
  
  return `data:${mimeType};base64,${btoa(binary)}`;
}

/**
 * 将 Blob 转换为 Base64 字符串
 * @param blob Blob 对象
 * @returns Promise<string> Base64 字符串
 */
export function blobToBase64(blob: Blob): Promise<string> {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = () => {
      if (typeof reader.result === 'string') {
        resolve(reader.result);
      } else {
        reject(new Error('Failed to convert blob to base64'));
      }
    };
    reader.onerror = () => reject(reader.error);
    reader.readAsDataURL(blob);
  });
}

/**
 * 将 Base64 字符串转换为 Blob
 * @param base64 Base64 字符串
 * @param mimeType MIME 类型
 * @returns Blob 对象
 */
export function base64ToBlob(base64: string, mimeType: string = 'image/png'): Blob {
  const byteCharacters = atob(base64.split(',')[1] || base64);
  const byteNumbers = new Array(byteCharacters.length);
  
  for (let i = 0; i < byteCharacters.length; i++) {
    byteNumbers[i] = byteCharacters.charCodeAt(i);
  }
  
  const byteArray = new Uint8Array(byteNumbers);
  return new Blob([byteArray], { type: mimeType });
}

/**
 * 检查字符串是否为有效的 Base64
 * @param str 要检查的字符串
 * @returns boolean
 */
export function isValidBase64(str: string): boolean {
  try {
    return btoa(atob(str)) === str;
  } catch (err) {
    return false;
  }
}
